<template>
  <div>
    <Row>
      <div style="margin-top: 8px; margin-right: 60px; float: right">
        <!-- <span
          id="todoPanel"
          style="cursor: pointer; color: #57a3f3"
          @click="switch2Manager"
          >Task manager</span
        >
        <Divider type="vertical" />
        <span id="ganttPanel" style="cursor: pointer" @click="switch2Content"
          >Gantt chart</span
        > -->
      </div>
      <Col id="taskPage" span="24">
        <div id="taskContainer" :style="{ height: contentHeight - 120 + 'px' }">
          <template v-if="!chartSwitch">
            <Row type="flex" justify="space-around">
              <Col span="7">
                <Card :padding="0" :border="false" dis-hover>
                  <h3 slot="title">未开始</h3>
                  <Button
                    slot="extra"
                    type="default"
                    class="createTaskBtn"
                    style="margin-top: -8px"
                    @click="createTaskModalShow()"
                    v-if="userInfo.role == 'admin' || userInfo.role == 'teacher'"
                    >添加任务</Button
                  >
                  <vue-scroll :ops="ops" :style="{ height: contentHeight - 150 + 'px' }">
                    <draggable
                      :disabled="true"
                      class="taskList"
                      element="ul"
                      :options="{ group: 'task' }"
                      v-model="taskTodo"
                      :style="{ height: contentHeight - 150 + 'px' }"
                    >
                      <div
                        v-for="(item, index) in taskTodo"
                        :key="index.taskId"
                        :padding="3"
                      >
                        <Card
                          style="margin: 5px; background-color: lightyellow"
                          v-if="item.type == 'syllabus'"
                        >
                          <div title="syllabus task">
                            <span style="float: left; padding: 0 2.5px">
                              <Icon type="ios-list" color="gray" :size="20" />
                            </span>
                            <span
                              style="padding: 5px; cursor: pointer"
                              @click="showTask(index, taskTodo)"
                            >
                              <strong
                                style="color: #57a3f3"
                                class="name"
                                :title="item.name"
                                >{{ item.name }}</strong
                              >
                            </span>
                            <div style="float: right">
                              <Rate
                                disabled
                                :count="1"
                                v-model="item.stars"
                                title="Importance"
                              />
                              <template
                                v-if="
                                  userInfo.role == 'admin' || userInfo.role == 'teacher'
                                "
                              >
                                <span title="Edit">
                                  <Icon
                                    type="ios-create"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                    @click="editOneTask(index, taskTodo)"
                                  />
                                </span>
                                <span
                                  style="
                                    margin-left: 5px;
                                    margin-right: 3px;
                                    cursor: pointer;
                                    color: gray;
                                  "
                                  title="Delete"
                                  @click="taskRemoveAssure(index, taskTodo)"
                                >
                                  <Icon type="ios-trash" :size="20" color="gray" />
                                </span>
                              </template>
                            </div>
                            <p
                              style="
                                word-break: break-word;
                                padding: 5px;
                                cursor: pointer;
                              "
                              @click="showTask(index, taskTodo)"
                            >
                              {{ item.description }}
                            </p>
                            <div style="display: flex; justify-content: space-between">
                              <Tag
                                color="default"
                                style="cursor: default; float: left"
                                title="Executor"
                                >{{ item.startTime | deadlineFilter }} -
                                {{ item.endTime | deadlineFilter }}</Tag
                              >
                              <Tag
                                color="default"
                                style="cursor: default"
                                title="Creator"
                                >{{ item.creatorName }}</Tag
                              >
                            </div>
                          </div>
                        </Card>
                        <Card style="margin: 5px" v-else>
                          <div title="Simple task">
                            <span style="float: left; padding: 0 2.5px">
                              <Icon type="ios-list" color="gray" :size="20" />
                            </span>
                            <span
                              style="padding: 5px; cursor: pointer"
                              @click="showTask(index, taskTodo)"
                            >
                              <strong
                                style="color: #57a3f3"
                                class="name"
                                :title="item.name"
                                >{{ item.name }}</strong
                              >
                            </span>
                            <div style="float: right">
                              <Rate
                                disabled
                                v-model="item.stars"
                                :count="1"
                                title="Importance"
                              />
                              <template
                                v-if="
                                  userInfo.role == 'admin' || userInfo.role == 'teacher'
                                "
                              >
                                <span title="Edit">
                                  <Icon
                                    type="ios-create"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                    @click="editOneTask(index, taskTodo)"
                                  />
                                </span>
                                <span
                                  style="
                                    margin-left: 5px;
                                    margin-right: 3px;
                                    cursor: pointer;
                                    color: gray;
                                  "
                                  title="Delete"
                                  @click="taskRemoveAssure(index, taskTodo)"
                                >
                                  <Icon type="ios-trash" :size="20" color="gray" />
                                </span>
                              </template>
                            </div>
                            <p
                              style="
                                word-break: break-word;
                                padding: 5px;
                                cursor: pointer;
                              "
                              @click="showTask(index, taskTodo)"
                            >
                              {{ item.description }}
                            </p>
                            <div style="display: flex; justify-content: space-between">
                              <Tag
                                color="default"
                                style="cursor: default; float: left"
                                title="Executor"
                                >{{ item.startTime | deadlineFilter }} -
                                {{ item.endTime | deadlineFilter }}</Tag
                              >
                              <Tag
                                color="default"
                                style="cursor: default"
                                title="Creator"
                                >{{ item.creatorName }}</Tag
                              >
                            </div>
                          </div>
                        </Card>
                      </div>
                      <Spin size="large" fix v-if="todoLoading"></Spin>
                    </draggable>
                  </vue-scroll>
                </Card>
              </Col>
              <Col span="7">
                <Card :padding="0" :border="false" dis-hover>
                  <h3 slot="title">进行中</h3>
                  <vue-scroll :ops="ops" :style="{ height: contentHeight - 150 + 'px' }">
                    <draggable
                      :disabled="true"
                      class="taskList"
                      element="ul"
                      :options="{ group: 'task' }"
                      v-model="taskDoing"
                      :style="{ height: contentHeight - 150 + 'px' }"
                    >
                      <div
                        v-for="(item, index) in taskDoing"
                        :key="index.taskId"
                        :padding="3"
                      >
                        <Card
                          style="margin: 5px; background-color: lightyellow"
                          v-if="item.type == 'syllabus'"
                        >
                          <div title="syllabus task">
                            <span
                              style="float: left; padding: 0 2.5px; cursor: pointer"
                              @click="showTask(index, taskDoing)"
                            >
                              <Icon
                                type="ios-information-circle-outline"
                                color="gray"
                                :size="20"
                              />
                            </span>
                            <span
                              style="padding: 5px; cursor: pointer"
                              @click="showTask(index, taskDoing)"
                            >
                              <strong
                                style="color: #57a3f3"
                                class="name"
                                :title="item.name"
                                >{{ item.name }}</strong
                              >
                            </span>
                            <div style="float: right" v-show="userRole != 'visitor'">
                              <Rate
                                disabled
                                v-model="item.stars"
                                :count="1"
                                title="Importance"
                              />
                              <template
                                v-if="
                                  userInfo.role == 'admin' || userInfo.role == 'teacher'
                                "
                              >
                                <span title="Edit">
                                  <Icon
                                    type="ios-create"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                    @click="editOneTask(index, taskDoing)"
                                  />
                                </span>
                                <span
                                  style="
                                    margin-left: 5px;
                                    margin-right: 3px;
                                    cursor: pointer;
                                    color: gray;
                                  "
                                  title="Delete"
                                  @click="taskRemoveAssure(index, taskDoing)"
                                >
                                  <Icon type="ios-trash" :size="20" color="gray" />
                                </span>
                              </template>
                            </div>
                          </div>
                          <p
                            style="word-break: break-word; padding: 5px; cursor: pointer"
                            @click="showTask(index, taskDoing)"
                          >
                            {{ item.description }}
                          </p>
                          <div style="display: flex; justify-content: space-between">
                            <Tag
                              color="default"
                              style="cursor: default; float: left"
                              title="Executor"
                              >{{ item.startTime | deadlineFilter }} -
                              {{ item.endTime | deadlineFilter }}</Tag
                            >
                            <Tag
                              color="default"
                              style="cursor: default"
                              title="Executor"
                              >{{ item.creatorName }}</Tag
                            >
                          </div>
                        </Card>
                        <Card style="margin: 5px" v-else>
                          <div title="Simple task">
                            <span style="float: left; padding: 0 2.5px">
                              <Icon
                                type="ios-information-circle-outline"
                                color="gray"
                                :size="20"
                              />
                            </span>
                            <span
                              style="padding: 5px; cursor: pointer"
                              @click="showTask(index, taskDoing)"
                            >
                              <strong
                                style="color: #57a3f3"
                                class="name"
                                :title="item.name"
                                >{{ item.name }}</strong
                              >
                            </span>
                            <div style="float: right" v-show="userRole != 'visitor'">
                              <Rate
                                disabled
                                v-model="item.stars"
                                :count="1"
                                title="Importance"
                              />
                              <template
                                v-if="
                                  userInfo.role == 'admin' || userInfo.role == 'teacher'
                                "
                              >
                                <span title="Edit">
                                  <Icon
                                    type="ios-create"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                    @click="editOneTask(index, taskDoing)"
                                  />
                                </span>
                                <span
                                  style="
                                    margin-left: 5px;
                                    margin-right: 3px;
                                    cursor: pointer;
                                    color: gray;
                                  "
                                  title="Delete"
                                  @click="taskRemoveAssure(index, taskDoing)"
                                >
                                  <Icon type="ios-trash" :size="20" color="gray" />
                                </span>
                                <span
                                  title="打包下载"
                                  v-if="item.type == 'homework'"
                                  @click="
                                    downDoingModal = true;
                                    getClassTaskSuffix(index, taskDoing);
                                  "
                                >
                                  <Icon
                                    type="md-download"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                  />
                                </span>
                              </template>
                            </div>
                          </div>
                          <p
                            style="word-break: break-word; padding: 5px; cursor: pointer"
                            @click="showTask(index, taskDoing)"
                          >
                            {{ item.description }}
                          </p>
                          <div style="display: flex; justify-content: space-between">
                            <Tag
                              color="default"
                              style="cursor: default; float: left"
                              title="Executor"
                              >{{ item.startTime | deadlineFilter }} -
                              {{ item.endTime | deadlineFilter }}
                            
                              </Tag
                            >
                            <!-- <Tag
                              color="default"
                              style="cursor: default; float: left"
                              title="Executor"
                        
                              >{{ item.duration }}
                            
                              </Tag
                            > -->
                            <Tag
                              color="default"
                              style="cursor: default"
                              title="Executor"
                              >{{ item.creatorName }}{{ item.creatorId }}</Tag
                            >
                          </div>
                        </Card>
                      </div>
                      <Spin size="large" fix v-if="doingLoading"></Spin>
                    </draggable>
                  </vue-scroll>
                </Card>
              </Col>
              <Col span="7">
                <Card :padding="0" :border="false" dis-hover>
                  <h3 slot="title">已完成</h3>
                  <vue-scroll :ops="ops" :style="{ height: contentHeight - 150 + 'px' }">
                    <draggable
                      :disabled="true"
                      class="taskList"
                      element="ul"
                      :options="{ group: 'task' }"
                      v-model="taskDone"
                      :style="{ height: contentHeight - 150 + 'px' }"
                    >
                      <div
                        v-for="(item, index) in taskDone"
                        :key="index.taskId"
                        :padding="3"
                      >
                        <Card
                          style="margin: 5px; background-color: lightyellow"
                          v-if="item.type == 'syllabus'"
                        >
                          <div title="syllabus task">
                            <span style="float: left; padding: 0 2.5px">
                              <Icon type="md-checkmark-circle-outline" />
                            </span>
                            <span
                              style="padding: 5px; cursor: pointer"
                              @click="showTask(index, taskDone)"
                            >
                              <strong
                                style="color: #57a3f3"
                                class="name"
                                :title="item.name"
                                >{{ item.name }}</strong
                              >
                            </span>
                            <div style="float: right" v-show="userRole != 'visitor'">
                              <Rate
                                disabled
                                v-model="item.stars"
                                :count="1"
                                title="Importance"
                              />
                              <template
                                v-if="
                                  userInfo.role == 'admin' || userInfo.role == 'teacher'
                                "
                              >
                                <span title="Edit">
                                  <Icon
                                    type="ios-create"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                    @click="editOneTask(index, taskDoing)"
                                  />
                                </span>
                                <span
                                  style="
                                    margin-left: 5px;
                                    margin-right: 3px;
                                    cursor: pointer;
                                    color: gray;
                                  "
                                  title="Delete"
                                  @click="taskRemoveAssure(index, taskDone)"
                                >
                                  <Icon type="ios-trash" :size="20" color="gray" />
                                </span>
                                <span
                                  style="
                                    margin-left: 5px;
                                    margin-right: 3px;
                                    cursor: pointer;
                                    color: gray;
                                  "
                                  title="查看考试成绩"
                                  v-if="item.type == 'test'"
                                  @click="previewQuestions(index, taskDone)"
                                >
                                  <Icon type="ios-eye" :size="20" color="gray" />
                                </span>
                              </template>
                            </div>
                            <p
                              style="
                                word-break: break-word;
                                padding: 5px;
                                cursor: pointer;
                              "
                              @click="showTask(index, taskDone)"
                            >
                              {{ item.description }}
                            </p>
                            <div style="display: flex; justify-content: space-between">
                              <Tag
                                color="default"
                                style="cursor: default; float: left"
                                title="Executor"
                                >{{ item.startTime | deadlineFilter }} -
                                {{ item.endTime | deadlineFilter }}</Tag
                              >
                              <Tag
                                color="default"
                                style="cursor: default"
                                title="Executor"
                                >{{ item.creatorName }}</Tag
                              >
                            </div>
                          </div>
                        </Card>
                        <Card style="margin: 5px" v-else>
                          <div title="Simple task">
                            <span style="float: left; padding: 0 2.5px">
                              <Icon type="md-checkmark-circle-outline" />
                            </span>
                            <span
                              style="padding: 5px; cursor: pointer"
                              @click="showTask(index, taskDone)"
                            >
                              <strong
                                style="color: #57a3f3"
                                class="name"
                                :title="item.name"
                                >{{ item.name }}</strong
                              >
                            </span>
                            <div style="float: right" v-show="userRole != 'visitor'">
                              <Rate
                                disabled
                                v-model="item.stars"
                                :count="1"
                                title="Importance"
                              />
                              <template
                                v-if="
                                  userInfo.role == 'admin' || userInfo.role == 'teacher'
                                "
                              >
                                <span title="Edit">
                                  <Icon
                                    type="ios-create"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                    @click="editOneTask(index, taskDone)"
                                  />
                                </span>
                                <span
                                  title="锁定任务后，学生用户将无法上传或修改作业，班级成员同时获得查看其他成员作业的权限"
                                  v-if="item.type == 'homework' && item.lock == false"
                                >
                                  <Icon
                                    type="md-unlock"
                                    color="lightgray"
                                    :size="20"
                                    style="cursor: pointer"
                                    @click="lockTask(index, taskDone, 'true')"
                                  />
                                </span>
                                <span
                                  title="解开锁定后，学生用户将获得上传或修改作业的权限"
                                  v-if="item.type == 'homework' && item.lock == true"
                                >
                                  <Icon
                                    type="md-lock"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                    @click="lockTask(index, taskDone, 'false')"
                                  />
                                </span>
                                <span
                                  style="
                                    margin-left: 5px;
                                    margin-right: 3px;
                                    cursor: pointer;
                                    color: gray;
                                  "
                                  title="Delete"
                                  @click="taskRemoveAssure(index, taskDone)"
                                >
                                  <Icon type="ios-trash" :size="20" color="gray" />
                                </span>

                                <span
                                  title="打包下载"
                                  v-if="item.type == 'homework'"
                                  @click="
                                    DoneModal = true;
                                    getClassTaskSuffix(index, taskDone);
                                  "
                                >
                                  <Icon
                                    type="md-download"
                                    color="gray"
                                    :size="20"
                                    style="cursor: pointer"
                                  />
                                </span>
                                <span
                                  style="
                                    margin-left: 5px;
                                    margin-right: 3px;
                                    cursor: pointer;
                                    color: gray;
                                  "
                                  title="查看考试成绩"
                                  v-if="item.type == 'test'"
                                  @click="previewQuestions(index, taskDone)"
                                >
                                  <Icon type="ios-eye" :size="20" color="gray" />
                                </span>
                              </template>
                            </div>
                            <p
                              style="
                                word-break: break-word;
                                padding: 5px;
                                cursor: pointer;
                              "
                              @click="showTask(index, taskDone)"
                            >
                              {{ item.description }}
                            </p>
                            <div style="display: flex; justify-content: space-between">
                              <Tag
                                color="default"
                                style="cursor: default; float: left"
                                title="Executor"
                                >{{ item.startTime | deadlineFilter }} -
                                {{ item.endTime | deadlineFilter }}</Tag
                              >
                              <Tag
                              color="default"
                              style="cursor: default"
                              title="Executor"
                              >{{ item.creatorName }}{{ item.creatorId }}</Tag
                            >
                            </div>
                          </div>
                        </Card>
                      </div>
                      <Spin size="large" fix v-if="doneLoading"></Spin>
                    </draggable>
                  </vue-scroll>
                </Card>
              </Col>
            </Row>
          </template>
          <div v-if="chartSwitch">
            <!-- <vue-scroll
              :ops="scrollOps"
              :style="{ height: contentHeight - 95 + 'px' }"
            > -->
            <task-content
              :taskInfo="selectTaskInfo"
              :taskDoing="taskDoing"
              @back2Task="switch2Manager"
              @turn2Folder="turn2Folder"
            ></task-content>
            <!-- </vue-scroll> -->
          </div>
        </div>
      </Col>
    </Row>
    <Modal
      v-model="DoneModal"
      title="选择需要下载的文件类型"
      @on-ok="compressDownloadBySuffix(index, taskDone, suffix)"
      @on-cancel="cancel"
    >
      <div
        style="border-bottom: 1px solid #e9e9e9; padding-bottom: 6px; margin-bottom: 6px"
      >
        <Checkbox
          :indeterminate="indeterminate"
          :value="checkAll"
          @click.prevent.native="handleCheckAll"
          >全选</Checkbox
        >
      </div>
      <CheckboxGroup v-model="checkAllGroup" @on-change="checkAllGroupChange">
        <Checkbox v-for="(file, item) in getfiles" :key="item" :label="file"></Checkbox>
      </CheckboxGroup>
    </Modal>
    <Modal
      v-model="downDoingModal"
      title="选择需要下载的文件类型"
      @on-ok="compressDownloadBySuffix(index, taskDoing, suffix)"
      @on-cancel="cancel"
    >
      <div
        style="border-bottom: 1px solid #e9e9e9; padding-bottom: 6px; margin-bottom: 6px"
      >
        <Checkbox
          :indeterminate="indeterminate"
          :value="checkAll"
          @click.prevent.native="handleCheckAll"
          >全选</Checkbox
        >
      </div>
      <CheckboxGroup v-model="checkAllGroup" @on-change="checkAllGroupChange">
        <Checkbox
          v-for="(file, index1) in getfiles"
          :key="index1"
          :label="file"
        ></Checkbox>
      </CheckboxGroup>
    </Modal>
    <Modal v-model="taskDeleteModal" title="Delete task" @on-ok="taskRemove()">
      <p>Do yout want to delete this task?</p>
    </Modal>
    <Modal v-model="createTaskModal" title="创建任务" width="800px">
      <Steps :current="addTaskStep" style="margin: auto; width: 60%">
        <Step title="基本信息"></Step>
        <Step title="详细内容"></Step>
      </Steps>
      <Form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="100"
        style="margin-left: 30px; margin-top: 30px"
        v-if="addTaskStep == 0"
      >
        <FormItem label="任务类型">
          <Row>
            <Col span="16">
              <RadioGroup v-model="formValidate.type">
                <Radio label="homework">作业任务</Radio>
                <Radio label="syllabus">课程大纲</Radio>
                <Radio label="expanding">课外拓展</Radio>
                <Radio label="notice">课程公告</Radio>
                <Radio label="test">在线考试</Radio>
              </RadioGroup>
              </Col
            >
            <Col>
              <FormItem v-if="formValidate.type !== 'test'" label prop="importance">
                <Checkbox v-model="formValidate.importance">重点标记</Checkbox>
              </FormItem>
            </Col>
          </Row>
        </FormItem>
        <FormItem v-if="formValidate.type !== 'test'" label="任务名称" prop="name">
          <Input
            v-model="formValidate.name"
            placeholder="填写任务名称…"
            style="width: 560px"
          />
        </FormItem>
        <Form-item v-if="formValidate.type == 'test'" label="选择试卷" prop="select">
          <Select
            v-model="formValidate.select"
            placeholder="请选择试卷"
            style="width: 560px"
          >
            <Option v-for="item in questionCreated" :value="item.id" :key="item">{{
              item.name
            }}</Option>
          </Select>
        </Form-item>
        <FormItem v-if="formValidate.type !== 'test'" label="任务描述" prop="description">
          <Input
            v-model="formValidate.description"
            type="textarea"
            placeholder="填写任务描述…"
            style="width: 560px"
            :autosize="{ minRows: 3 }"
          />
        </FormItem>
        <FormItem label="起止时间" prop="timeRange">
          <DatePicker
            v-model="formValidate.timeRange"
            type="daterange"
            format="yyyy-MM-dd"
            placeholder="选择时间…"
            style="width: 560px"
          ></DatePicker>
        </FormItem>
        <FormItem v-if="formValidate.type == 'test'" label="考试时长" prop="duration">
          <Time-picker
            v-model="formValidate.duration"
            placeholder="选择时间"
          ></Time-picker>
        </FormItem>
        <FormItem label prop="createFolder" v-if="formValidate.type == 'homework'">
          <Checkbox v-model="formValidate.createFolder">快速创建成员文件夹</Checkbox>
        </FormItem>
      </Form>
      <task-detail
        :userInfo="userInfo"
        :formValidate="formValidate"
        @createSuccess="createSuccess(data)"
        ref="taskDetail"
        v-if="addTaskStep == 1 && formValidate.type !== 'test'"
        
      ></task-detail>
      <div slot="footer">
        <Button v-if="formValidate.type !== 'test'&& addTaskStep == 0 " type="primary" @click="goNextStep('formValidate')" 
          >下一步</Button
        >
        <Button type="warning" @click="goPreStep()" v-if="addTaskStep == 1"
          >上一步</Button
        >
        <Button type="success" @click="createTaskModal=false, createTask('formValidate')" v-if="addTaskStep == 1 || formValidate.type == 'test'"
          >创建</Button
        >
      </div>
    </Modal>
    <Modal
      v-model="editTaskModal"
      title="编辑任务"
      @on-ok="updateTask('formValidate')"
      ok-text="Ok"
      cancel-text="Cancel"
      width="800px"
      :closable="false"
    >
      <Form
        ref="editFormValidate"
        :model="editFormValidate"
        :rules="ruleValidate"
        :label-width="100"
        style="margin-left: 30px"
      >
        <FormItem label="任务类型">
          <Row>
            <Col span="16">
              <RadioGroup v-model="editFormValidate.type">
                <Radio label="homework">作业任务</Radio>
                <Radio label="syllabus">课程大纲</Radio>
                <Radio label="expanding">课外拓展</Radio>
                <Radio label="notice">课程公告</Radio>
                <Radio label="test">在线考试</Radio>
              </RadioGroup></Col
            >
            <Col>
              <FormItem label prop="importance">
                <Checkbox v-model="editFormValidate.importance">重点标记</Checkbox>
              </FormItem>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="任务名称" prop="name">
          <Input
            v-model="editFormValidate.name"
            placeholder="Fill in the name of task..."
            style="width: 560px"
          />
        </FormItem>
        <Form-item v-if="editFormValidate.type == 'test'" label="选择试卷" prop="select">
          <Select
            v-model="editFormValidate.select"
            placeholder="请选择试卷"
            style="width: 560px"
          >
            <Option v-for="item in questionCreated" :key="item">{{ item.name }}</Option>
          </Select>
        </Form-item>
        <FormItem label="任务描述" prop="description">
          <Input
            v-model="editFormValidate.description"
            type="textarea"
            placeholder="Fill in the description of task..."
            style="width: 560px"
            :autosize="{ minRows: 4 }"
          />
        </FormItem>
        <FormItem label="起止时间" prop="timeRange">
          <DatePicker
            v-model="editFormValidate.timeRange"
            type="daterange"
            format="yyyy-MM-dd"
            placeholder="Select start time..."
            style="width: 560px"
          ></DatePicker>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="editTaskModal = false">取消</Button>
        <Button type="primary" @click="updateTask('editFormValidate')">确定修改</Button>
      </div>
    </Modal>
    <Modal v-model="examDetailShow" title="进入考试">
      <!-- <iframe :src="previewUrl" frameborder="0" style="width: 100%;height:100%; min-height:450px;"></iframe> -->
      <Alert show-icon style="margin-top: 15px; width: 100%" >
        提示：
        <Icon size="50px" type="ios-bulb-outline" slot="icon"></Icon>
        <span>是否进入考试?</span>
      
      </Alert>
      <div slot="footer">
        <Button type="success" @click="enterTestItem()">进入</Button>
      </div>
    </Modal>
    <Modal
      v-model="taskDetailModal"
      :title="taskInfo.type == 'activity' ? 'Activity task' : 'Simple task'"
      width="800px"
    >
      <div class="taskFormItem">
        <span style="width: 15%">Task name</span>
        <Input  style="width: 600px" v-model="taskInfo.name" readonly />
      </div>
      <div class="taskFormItem">
        <span style="width: 15%">Description</span>
        <Input
          style="width: 600px"
          type="textarea"
          v-model="taskInfo.description"
          :autosize="{ minRows: 4 }"
          readonly
        />
      </div>
      <div class="taskFormItem" style="margin-bottom: 10px">
        <span style="width: 15%">Time range</span>
        <DatePicker
          v-model="taskInfo.timeRange"
          type="daterange"
          format="yyyy-MM-dd"
          style="width: 600px"
          readonly
        ></DatePicker>
      </div>
    </Modal>
  </div>
</template>
<script>
import { get, post, del, put } from "@/axios";
import dayjs from "dayjs";
import draggable from "vuedraggable";
import GanttElastic from "gantt-elastic";
import taskDetail from "./taskDetail.vue";
import taskContent from "./taskContent.vue";
export default {
  components: {
    draggable,
    dayjs,
    ganttElastic: GanttElastic,
    taskDetail,
    taskContent,
  },
  props: ["classTaskList"],
  data() {
    return {
      questionCreated: [],
      userRole: "visitor",
      index: 0,
      idtest: "",
      examDetailShow:false,
      todoLoading: true,
      doingLoading: true,
      editTaskState: "",
      removeTaskState: "",
      socketId: "",
      doneLoading: true,
      DoneModal: false,
      downDoingModal: false,
      // downDoingModal: false,
      // downDoneModal: false,
      downIndex: 0,
      indeterminate: false,
      checkAll: true,
      checkAllGroup: [],
      getfiles: [],
      suffix: "",
      ops: {
        bar: {
          background: "#808695",
        },
      },
      scrollOps: {
        bar: {
          background: "#808080",
          keepShow: true,
          size: "8px",
        },
        rail: {
          background: "#d7d7d7",
          opacity: 0.8,
          size: "10px",
        },
      },
      addTaskStep: 0,
      // 后台获取的subproject下的task列表
      taskList: [],
      selectTaskIndex: 0,
      taskDeleteModal: false,
      // 创建任务的模态框
      createTaskModal: false,
      // 编辑任务的模态框
      editTaskModal: false,
      taskDetailModal: false,
      //恢复登录的模态框
      tempLoginModal: false,
      isClassTask: true,
      //task相关
      taskInfo: {},
      taskTodo: [],
      taskDoing: [],
      taskDone: [],
      MoveCount: 0,
      // 动态记录相关
      formValidate: {
        name: "",
        select: "",
        description: "",
        type: "homework",
        timeRange: "",
        duration: "",
        createFolder: true,
        importance: false,
      },
      editFormValidate: {
        name: "",
        select: "",
        description: "",
        type: "homework",
        timeRange: "",
        duration: "",
        importance: false,
      },
      ruleValidate: {
        name: [{ required: true, message: "请输入名称...", trigger: "blur" }],
        select: [{ required: true, message: "请选择试卷...", trigger: "blur" }],
        duration: [{ required: true, message: "请输入考试时长...", trigger: "blur" }],
        timeRange: [
          {
            type: "array",
            required: true,
            trigger: "blur",
            fields: {
              0: { required: true, type: "date" },
              1: { required: true, type: "date" },
            },
          },
        ],
      },
      // style
      contentHeight: "",
      chartSwitch: false, // 切换至任务详情
      selectTaskInfo: {},
    };
  },
  created() {
    this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.initSize();
  },
  watch: {},
  mounted() {
    // this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.dataSever = this.$store.getters.dataSever;
    this.classId = window.location.href.split("/classInfo?id=")[1].split("&content")[0];
    this.roleIdentity();
    this.inquiryTask();
    window.addEventListener("resize", this.initSize);
    this.viewTests();
  },

  beforeRouteLeave(to, from, next) {
    next();
  },
  beforeDestroy: function () {
    window.removeEventListener("resize", this.initSize);
  },
  methods: {
    async previewQuestions(index, taskList) {
      console.log(taskList[index].taskId);
      let taskId = taskList[index].taskId;
      try {
        let res = await get("/visualResourceLibrary/class/task/byId/" + taskId);
        // console.log(res.data.data);
        let testId = res.data.data.contents[0];
        try {
          let res = await get(
            "/visualResourceLibrary/questionnaire/test/statistics/" +
              taskId +
              "/" +
              testId
          );
          // console.log(res.data.data);
          this.$router.push({
            path: "/Static",
            query: { value: res.data.data },
          });
        } catch (e) {
          this.$Message.error("修改失败");
          console.log(e);
        }
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async viewTests() {
      let page = 0;
      let size = 100;
      try {
        let res = await get(
          "/visualResourceLibrary/questionnaire/test/" + page + "/" + size
        );
        // console.log(res.data.data);
        this.questionCreated = res.data.data.content;
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async publishTest() {
      let formData = new FormData();
      formData.append("testId", this.formValidate.select);
      formData.append("classId", this.classId);
      formData.append("isClassTask", this.isClassTask);
      var duration = this.formValidate.duration.split(":"); // split it at the colons

      // minutes are worth 60 seconds. Hours are worth 60 minutes.
      var seconds = +duration[0] * 60 * 60 + +duration[1] * 60 + +duration[2];

      formData.append("duration", seconds);
      formData.append("startTime", this.formValidate.timeRange[0]);
      formData.append("endTime", this.formValidate.timeRange[1]);

      try {
        let res = await post(
          "/visualResourceLibrary/questionnaire/test/publish",
          formData
        );
        this.$Message.success("创建成功");
        location.reload();
        // console.log(res.data.data);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async enterTestItem() {
      try {
        let res = await get("/visualResourceLibrary/questionnaire/test/enter/" + this.idtest);
        // console.log(res.data.data);
        if (res.data.data.testItems.finished == false) {
          this.$router.push({
            path: "/answerPage",
            query: { value: res.data.data },
          });
        } else {
          this.$Message.info("试卷已提交或已结束");
        }

        // this.$router.push({path:'/answerPage',query: { examName:this.questionCreated.name}});
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    initSize() {
      this.contentHeight = window.innerHeight - 140;
    },
    roleIdentity() {
      this.userRole = this.userInfo.role;
    },
    changeLoginModal(status) {
      this.tempLoginModal = status;
    },
    //创建任务
    createTaskModalShow() {
      this.addTaskStep = 0;
      let taskDefult = {
        name: "",
        description: "",
        select: "",
        type: "homework",
        timeRange: [],
        state: "todo",
        createFolder: true,
        importance: false,
      };
      this.$set(this, "taskInfo", taskDefult);
      this.$set(this, "formValidate", taskDefult);
      this.createTaskModal = true;
    },
    goNextStep(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.addTaskStep = 1;
        } else {
          this.$Message.error("Please enter the necessary information!");
        }
      });
    },
    goPreStep() {
      this.addTaskStep = 0;
    },
    createTask(name) {
      if (this.formValidate.type == "test") {
        this.publishTest();
      } else {
        this.$refs.taskDetail.createTask();
      }
      //父子组件传值  在task-detail中提交
      // console.log(this.formValidate);
    },
    createSuccess(data) {
      this.createTaskModal = false;
      location.reload();
    },
    addNewTask(newTaskObject) {
      this.taskTodo.push(newTaskObject);
    },
    changeImportance(task) {
      let taskForm = new URLSearchParams();
      taskForm.append("taskId", task.taskId);
      taskForm.append("importance", task.importance);
      this.axios
        .post("/GeoProblemSolving/task/update", taskForm)
        .then((res) => {
          if (res.data == "Offline") {
            this.$store.commit("userLogout");
            // this.$router.push({ name: "Login" });
            this.tempLoginModal = true;
          } else if (res.data != "None" && res.data != "Fail") {
            this.$Message.info("Changed the importance of one task.");
          } else {
            this.$Message.error("Fail!");
          }
        })
        .catch((err) => {
          console.log(err.data);
        });
    },
    //打开task编辑器
    editOneTask(index, taskList) {
      console.log(taskList[index]);
      this.editTaskModal = true;
      this.editFormValidate.taskId = taskList[index].taskId;
      this.editFormValidate.name = taskList[index].name;
      this.editFormValidate.type = taskList[index].type;
      this.editFormValidate.select = taskList[index].select;
      this.editFormValidate.description = taskList[index].description;
      this.editFormValidate.importance =
        taskList[index].importance == "true" ? true : false;
      this.editFormValidate.timeRange = [
        new Date(taskList[index].startTime),
        new Date(taskList[index].endTime),
      ];
      // console.log(this.editFormValidate);
    },
    showTask(index, taskList) {
      if (taskList[index].type == "test") {
        if( this.userInfo.role == 'teacher'){  
          this.$Message.warning("老师不要参加考试");

        }
        else{
        this.idtest = taskList[index].contents[0];
        this.examDetailShow=true;
        }
        // this.enterTestItem(this.idtest);
      } else {
        this.selectTaskInfo = taskList[index];
        this.switch2Content();
      }
    },
    updateTaskList(taskObject) {
      taskObject.importance = taskObject.importance ? 1 : 0;
      switch (taskObject.state) {
        case "todo": {
          let taskList = this.taskTodo;
          for (var i = 0; i < taskList.length; i++) {
            if (taskList[i].taskId == taskObject.taskId) {
              this.$set(this.taskTodo, i, taskObject);
              break;
            }
          }
          break;
        }
        case "doing": {
          let taskList = this.taskDoing;
          for (var i = 0; i < taskList.length; i++) {
            if (taskList[i].taskId == taskObject.taskId) {
              this.$set(this.taskDoing, i, taskObject);
              break;
            }
          }
          break;
        }
        case "done": {
          let taskList = this.taskDone;
          for (var i = 0; i < taskList.length; i++) {
            if (taskList[i].taskId == taskObject.taskId) {
              this.$set(this.taskDone, i, taskObject);
              break;
            }
          }
          break;
        }
      }
    },
    //更新某个task
    async updateTask(name) {
      let importance = this.editFormValidate.importance ? "true" : "false";
      let taskForm = new FormData();
      taskForm.append("taskId", this.editFormValidate.taskId);
      taskForm.append("name", this.editFormValidate.name);
      taskForm.append("type", this.editFormValidate.type);
      taskForm.append("select", this.editFormValidate.select);
      taskForm.append("description", this.editFormValidate.description);
      taskForm.append("startTime", new Date(this.editFormValidate.timeRange[0]));
      taskForm.append("endTime", new Date(this.editFormValidate.timeRange[1]));
      taskForm.append("importance", importance);

      let tempTaskForm = {
        taskId: this.editFormValidate.taskId,
        name: this.editFormValidate.name,
        select: this.editFormValidate.select,
        description: this.editFormValidate.description,
        startTime: new Date(this.editFormValidate.timeRange[0]),
        endTime: new Date(this.editFormValidate.timeRange[1]),
        importance: importance,
      };
      try {
        let res = await post("/visualResourceLibrary/class/task/update", taskForm);
        console.log(res.data.data);
        location.reload();
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    //查询task
    inquiryTask() {
      setTimeout(() => {
        for (let i = 0; i < this.classTaskList.length; i++) {
          this.classTaskList[i].stars =
            this.classTaskList[i].importance == "true" ? 1 : 0;
          let now = new Date();
          let start = new Date(this.classTaskList[i].startTime);
          let end = new Date(this.classTaskList[i].endTime);
          if (now < start) {
            // todo
            this.taskTodo.push(this.classTaskList[i]);
          } else if (now >= start && now <= end) {
            // doing
            this.taskDoing.push(this.classTaskList[i]);
          } else {
            // done
            this.taskDone.push(this.classTaskList[i]);
          }
        }
        // console.log(this.taskDoing);
        this.todoLoading = false;
        this.doingLoading = false;
        this.doneLoading = false;
      }, 1000);
    },
    setMoveCount() {
      this.MoveCount = 2;
    },
    addMoveTask(taskList, type) {
      this.MoveCount--;
      this.taskOrderUpdate(taskList, type);
    },
    removeMoveTask(taskList, type) {
      this.MoveCount--;
      this.taskOrderUpdate(taskList, type);
    },
    updateMoveTask(taskList, type) {
      this.MoveCount -= 2;
      this.taskOrderUpdate(taskList, type);
    },
    taskOrderUpdate(taskList, type) {
      let thisUserName = this.$store.getters.userName;
      let stateChangeIndex = 0;
      let count = taskList.length;
      for (let i = 0; i < taskList.length; i++) {
        let thisTask = taskList[i];
        if (thisTask.order != i || thisTask.state != type) {
          if (thisTask.state != type) {
            stateChangeIndex = i;
            let taskUpdateObj = new URLSearchParams();
            taskUpdateObj.append("taskId", taskList[i]["taskId"]);
            taskUpdateObj.append("order", i);
            taskUpdateObj.append("state", type);
            taskUpdateObj.append("managerName", thisUserName);
            taskList[stateChangeIndex].order = stateChangeIndex;
            taskList[stateChangeIndex].managerName = thisUserName;
            taskList[stateChangeIndex].state = type;
            this.axios
              .post("/GeoProblemSolving/task/update", taskUpdateObj)
              .then((res) => {
                count--;
                if (res.data == "Offline") {
                  this.$store.commit("userLogout");
                  this.tempLoginModal = true;
                } else if (res.data != "Fail") {
                  //更新数组
                  // taskList[stateChangeIndex].order = stateChangeIndex;
                  // taskList[stateChangeIndex].managerName = thisUserName;
                  // taskList[stateChangeIndex].state = type;
                }
              })
              .catch((err) => {
                console.log(err.data);
              });
          } else {
            let taskUpdateObj = new URLSearchParams();
            taskUpdateObj.append("taskId", taskList[i]["taskId"]);
            taskUpdateObj.append("order", i);
            taskUpdateObj.append("state", type);
            this.axios
              .post("/GeoProblemSolving/task/update", taskUpdateObj)
              .then((res) => {
                count--;
                if (res.data == "Offline") {
                  this.$store.commit("userLogout");
                  // this.$router.push({ name: "Login" });
                  this.tempLoginModal = true;
                } else if (res.data != "Fail") {
                  taskList[i].order = i;
                }
              })
              .catch((err) => {
                console.log(err.data);
              });
          }
        }
      }
    },
    taskRemoveAssure(index, taskList) {
      console.log(index);
      this.taskDeleteModal = true;
      this.selectTaskIndex = index;
      this.removeTaskState = taskList[index].state;
      this.taskList = taskList;
    },
    async lockTask(index, taskList, lockState) {
      try {
        let res = await post(
          "/visualResourceLibrary/class/task/lock/" + taskList[index].taskId,
          lockState
        );
        if (lockState == "true") {
          this.$Message.success("锁定任务成功！");
        } else {
          this.$Message.success("揭开锁定成功！");
        }
        taskList[index].lock = !taskList[index].lock;
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async getClassTaskSuffix(index, taskList) {
      // 因为index传不到下载的函数里 ，先把index存起来，传到下载的函数里
      this.downIndex = index;
      console.log(this.downIndex);
      try {
        let res = await get(
          "/visualResourceLibrary/class/task/getClassTaskSuffix/" + taskList[index].taskId
        );
        // console.log(res.data.data);
        this.$Message.success("请求发送成功");
        this.checkAllGroup = res.data.data;
        this.getfiles = res.data.data;
        // console.log(checkAllGroup);
        // console.log(getfiles);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async compressDownload(index, taskList) {
      try {
        let res = await get(
          "/visualResourceLibrary/class/task/compressDownload/" + taskList[index].taskId
        );
        this.$Message.success("请求发送成功！稍后在个人资源中心中下载课程文件！");
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async compressDownloadAll(taskList) {
      try {
        let ids = "";
        for (let i = 0; i < taskList.length; i++) {
          if (i == 0) {
            ids += taskList[i].taskId;
          } else {
            ids += "," + taskList[i].taskId;
          }
        }
        let res = await get(
          "/visualResourceLibrary/class/task/compressDownloadAll/" + ids
        );
        console.log(res);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async compressDownloadBySuffix(index, taskList, suffix) {
      index = this.downIndex;
      const separator = ",";
      suffix = this.checkAllGroup.join(separator);
      try {
        let res = await get(
          "/visualResourceLibrary/class/task/compressDownloadBySuffix/" +
            taskList[index].taskId +
            "/" +
            suffix
        );
        this.checkAllGroup = [];
        this.getfiles = [];
        this.indeterminate = false;
        this.checkAll = true;
        this.$Message.success(
          "请求发送成功！稍后在个人资源中心中下载课程文件！"
        );
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    async taskRemove() {
      try {
        let res = await del(
          "/visualResourceLibrary/class/task/" +
            this.taskList[this.selectTaskIndex]["taskId"]
        );
        this.$Message.success("删除成功");
        this.taskList.splice(this.selectTaskIndex, 1);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },

    switch2Manager() {
      this.chartSwitch = false;
      // $("#todoPanel").css("color", "#57a3f3");
      // $("#ganttPanel").css("color", "black");
    },
    switch2Content() {
      // $("#todoPanel").css("color", "black");
      // $("#ganttPanel").css("color", "#57a3f3");
      this.chartSwitch = true;
   
    },
    turn2Folder(folderId) {
      this.chartSwitch = false;
      this.$emit("turn2Folder", folderId);
    },
    async compressDownloadBySuffix(index, taskList, suffix) {
      index = this.downIndex;
      const separator = ",";
      suffix = this.checkAllGroup.join(separator);

      //  if(taskType == 'taskDoing'){
      //   taskId = this.taskDoing[index].taskId;
      //  }else if(taskType == 'taskDone'){
      //   taskId = this.taskDone[index].taskId;
      //  }
      try {
        let res = await get(
          "/visualResourceLibrary/class/task/compressDownloadBySuffix/" +
            taskList[index].taskId +
            "/" +
            suffix
        );
        this.checkAllGroup = [];
        this.getfiles = [];
        this.indeterminate = false;
        this.checkAll = true;
        this.$Message.success("请求发送成功！稍后在个人资源中心中下载课程文件！");
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    cancel() {
      this.$Message.info("Clicked cancel");
      this.checkAllGroup = [];
      this.getfiles = [];
      this.indeterminate = false;
      this.checkAll = true;
    },
    handleCheckAll() {
      if (this.indeterminate) {
        this.checkAll = false;
      } else {
        this.checkAll = !this.checkAll;
      }
      this.indeterminate = false;

      if (this.checkAll) {
        this.checkAllGroup = this.getfiles;
      } else {
        this.checkAllGroup = [];
      }
    },
    checkAllGroupChange(data) {
      if (data.length === this.getfiles.length) {
        this.indeterminate = false;
        this.checkAll = true;
      } else if (data.length > 0) {
        this.indeterminate = true;
        this.checkAll = false;
      } else {
        this.indeterminate = false;
        this.checkAll = false;
      }
    },
  },
  filters: {
    filterSizeType(value) {
      if (value === 0) return "0 B";
      let k = 1024;
      let sizes = ["B", "KB", "MB", "GB"];
      let i = Math.floor(Math.log(value) / Math.log(k));
      return (value / Math.pow(k, i)).toPrecision(4) + " " + sizes[i];
    },
    filterTimeStyle(str) {
      return (str = new Date(str).toLocaleString());
    },
    deadlineFilter(str) {
      var dateTime = new Date(str);
      dateTime = dateTime.setDate(dateTime.getDate() - 1);
      let date = new Date(dateTime);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      const time = y + "-" + m + "-" + d + " 23:59:59";
      return time;
    },
  },
};
</script>
<style scoped>
.createTaskBtn {
  font-size: 10px;
}
.createTaskBtn:hover {
  color: white;
  background: #47cb89;
}
.title {
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  border-bottom: 1px solid lightgray;
}

.taskFormItem {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.taskFormItem span {
  text-align: center;
}
#taskContainer {
  padding: 10px;
  background-color: white;
}
.taskList {
  min-height: 60px;
  background: #f7f7f7;
}
.name {
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 120px;
}
</style>
